#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>

#define ERR_EXIT(m)\
do\
{\
    perror(m);\
    exit(EXIT_FAILURE);\
}while(0)

const char* PATHNAME = ".";
const int PROJ_ID = 1; 

int main(){
    key_t key = ftok(PATHNAME,PROJ_ID);
    
    const size_t SHM_SIZE = sizeof(int);
    int shmid = shmget(key,SHM_SIZE,IPC_CREAT|0666);
    if(shmid == -1)ERR_EXIT("shmget");
    
    int* pnum = (int*)shmat(shmid,NULL,0);
    if(pnum == (void*)-1)ERR_EXIT("shmat");

    *pnum = 0x4f4f4f4f;
    printf("*pnum:%d\n",*pnum);
    
    struct shminfo shminfo;
    if(shmctl(0,IPC_INFO,(struct shmid_ds*)(&shminfo)) == -1)ERR_EXIT("shmctl");  
    std::cout<<"shminfo.shmall:"<<shminfo.shmall<<std::endl;
    std::cout<<"shminfo.shmax:"<<shminfo.shmmax<<std::endl;
    std::cout<<"shminfo.shmmin:"<<shminfo.shmmin<<std::endl;
    std::cout<<"shminfo.shmmni:"<<shminfo.shmmni<<std::endl;
    std::cout<<"shminfo.shmseg:"<<shminfo.shmseg<<std::endl;


    struct shmid_ds shm_info;
    if(shmctl(shmid,SHM_STAT,&shm_info) == -1)ERR_EXIT("shmctl");  
    std::cout <<"shmid_ds.shm_perm.uid:"<<shm_info.shm_perm.uid<<std::endl;
    std::cout <<"pid:"<<getpid()<<std::endl;
    std::cout <<"shmid_ds.shmlpid:"<<shm_info.shm_lpid<<std::endl;
    std::cout <<"shmid_ds.shmcpid:"<<shm_info.shm_cpid<<std::endl;
    std::cout <<"shmid_ds.shm_perm.__key:"<<shm_info.shm_perm.__key<<std::endl;
    printf("key :%d\n",key); 
    // shmctl(shmid,IPC_RMID,NULL);
    if(shmdt(pnum) == -1)ERR_EXIT("shmdt");

    return 0;
}


